package com.jl.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.BASE64;
import com.jl.model.*;
import com.jl.model.in.DeviceIn;
import com.jl.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 故障信息表 前端控制器
 * </p>
 *
 * @author JiangJian
 * @since 2019-03-06
 */
@Controller
@RequestMapping("/faultInfo")
public class FaultInfoController extends BaseController {

    @Autowired
    private IFaultInfoService faultInfoService;

    @Autowired
    private IDeviceService deviceService;

    @GetMapping("/faultInfoDataGrid")
    @RequiresPermissions("/faultInfo/faultInfoDataGrid")
    public String faultInfoList() {
        return "faultInfo_list";
    }

    @GetMapping("/faultInfoDetail")
    @RequiresPermissions("/faultInfo/faultInfoDetail")
    public String faultDeatil(ModelMap mp, Long id) {
        mp.put("id", id);
        return "faultInfo_detail";
    }

    /**
     * 跳转到弹出窗添加故障信息
     *
     * @param mp
     * @param deviceId
     * @return
     */
    @GetMapping("/iframeAdd")
    @RequiresPermissions("/faultInfo/iframeAdd")
    public String toIframeAddFaultInfoPage(ModelMap mp, Long deviceId,Long modelId) {
        mp.put("deviceId", deviceId);
        mp.put("modelId", modelId);
        return "faultInfoIframe_add";
    }

    @PostMapping("/iframeAdd")
    @RequiresPermissions("/faultInfo/iframeAdd")
    @ResponseBody
    public ResultData iframeAddFaultInfo(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        FaultInfo faultInfo = JSON.parseObject(value, FaultInfo.class);
        DeviceIn deviceIn = deviceService.selectDeviceInById(faultInfo.getDeviceId());
        if (null != deviceIn) {
            faultInfo.setDeviceName(deviceIn.getName());
            faultInfo.setDeviceNumber(deviceIn.getNumber());
            faultInfo.setModelId(deviceIn.getModelId());
            faultInfo.setModelName(deviceIn.getModelName());
            faultInfo.setProductionLine(deviceIn.getProductionLine());
            faultInfo.setLineName(deviceIn.getProductionName());
        } else {
            return fail();
        }
        List<String> tipsComponent = new ArrayList<>();
        faultInfoService.saveFaultInfo(getShiroUser(), faultInfo, tipsComponent);
        return success(tipsComponent);
    }

    @GetMapping("/add")
    @RequiresPermissions("/faultInfo/add")
    public String addFaultInfoPage(ModelMap mp, Long id) {
        mp.put("id", id);
        return "faultInfo_add";
    }

    @PostMapping("/add")
    @RequiresPermissions("/faultInfo/add")
    @ResponseBody
    public ResultData addFaultInfo(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        FaultInfo faultInfo = JSON.parseObject(value, FaultInfo.class);
        List<String> tipsComponent = new ArrayList<>();
        faultInfoService.saveFaultInfo(getShiroUser(), faultInfo, tipsComponent);
        return success(tipsComponent);
    }

    @GetMapping("/edit")
    @RequiresPermissions("/faultInfo/edit")
    public String editFaultInfoPage(ModelMap mp, Long id) {
        mp.put("id", id);
        return "faultInfo_add";
    }

    @PostMapping("/edit")
    @RequiresPermissions("/faultInfo/edit")
    @ResponseBody
    public ResultData editFaultInfo(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        FaultInfo faultInfo = JSON.parseObject(value, FaultInfo.class);
        Date now = new Date();
        List<String> tipsComponent = new ArrayList<>();
        faultInfo.setGmtModified(now);
        faultInfo.setModifyId(getUserId());
        faultInfoService.updateById(faultInfo);
        return success(tipsComponent);
    }

    @PostMapping("/delete")
    @RequiresPermissions("/faultInfo/delete")
    @ResponseBody
    public ResultData deletesFaultInfo(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value, Long.class);
        boolean b = faultInfoService.removeByIds(ids);
        if (b) {
            return success();
        }
        return fail();
    }

    @PostMapping("/dataGrid")
    @RequiresPermissions("/faultInfo/dataGrid")
    @ResponseBody
    public ResultData faultInfoDataGrid(Long current, Long pageSize, String searchCol, String searchValue,String json) {
        if (current == null || pageSize == null) {
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        PageDataInfo<Map<String, Object>> pageDataInfo = new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        QueryWrapper<FaultInfo> queryWrapper = new QueryWrapper<>();

        if(StringUtils.isNotBlank(json)){
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(null!=jsonObject.getLong("modelId") && jsonObject.getLong("modelId")!=0){
                queryWrapper.eq("t.model_id",jsonObject.getLong("modelId"));
            }
            if(null!=jsonObject.getLong("productionLine") && jsonObject.getLong("productionLine")!=0){
                queryWrapper.eq("t.production_line",jsonObject.getLong("productionLine"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("deviceNumber"))){
                queryWrapper.like("t.device_number",jsonObject.getString("deviceNumber"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("symptom"))){
                queryWrapper.like("t.symptom",jsonObject.getString("symptom"));
            }

            if(StringUtils.isNotBlank(jsonObject.getString("faultTime"))){
                queryWrapper.like("t.fault_time",jsonObject.getString("faultTime"));
            }
            if(null!=jsonObject.getInteger("stopDuration") && jsonObject.getInteger("stopDuration")!=0){
                queryWrapper.ge("t.stop_duration",jsonObject.getInteger("stopDuration"));
            }
            if(null!=jsonObject.getLong("keyWordId") && jsonObject.getLong("keyWordId")!=0){
                queryWrapper.apply("FIND_IN_SET({0}, t.key_word_id)",jsonObject.getLong("keyWordId"));
            }

        }else{
            if (StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)) {
                if (Constants.ID.equals(searchCol)) {
                    queryWrapper.eq("t.id", searchValue);
                } else {
                    queryWrapper.like("t." + searchCol, searchValue);
                }
            }
        }

        faultInfoService.selectFaultInfoDataGrid(pageDataInfo, queryWrapper);
        return success(pageDataInfo);
    }

    @PostMapping("/addAcceptNum")
    @RequiresPermissions("/faultInfo/faultInfoDataGrid")
    @ResponseBody
    public ResultData addFaultAcceptNum(Long id) {
        boolean b = faultInfoService.addFaultInfoAcceptNum(id);
        if (b) {
            return success();
        } else {
            return fail();
        }
    }

}
